package com.example.tcpLearn.tcp6;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("HTTP服务启动：http://localhost:" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> handleClient(socket)).start();
        }
    }

    private static void handleClient(Socket socket) {
        try {
            /**
             * 读取 HTTP 请求
             */
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder requestHeader = new StringBuilder();
            while (!(line = bufferedReader.readLine()).isEmpty()) {
                requestHeader.append(line).append("\r\n");
            }
            System.out.println("收到请求：\n" + requestHeader);
            /**
             * 构造 HTTP 响应
             */
            String html = "<html>" +
                    "<body>" +
                    "<h1>Hello, this is Java HTTP Server!</h1>" +
                    "</body>" +
                    "</html>";
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type: text/html; charset=UTF-8\r\n" +
                    "Content-Length:" + html.getBytes().length + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" + html;
            /**
             * 写入响应
             */
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(response.getBytes());
            outputStream.flush();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
